package cn.qingyun.gis.modules.express.util;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.qingyun.gis.modules.express.entity.Point;
import cn.qingyun.gis.modules.express.service.IGdRestApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

@Component
@Slf4j
public class LocationTool {

    static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    // π
    static double pi = 3.1415926535897932384626;
    // 长半轴
    static double a = 6378245.0;
    // 扁率
    static double ee = 0.00669342162296594323;


    @Resource
    public void setiGdRestApiService(IGdRestApiService iGdRestApiService) {
        LocationTool.iGdRestApiService = iGdRestApiService;
    }

    private static IGdRestApiService iGdRestApiService;

    /**
     * 调用高德测试接口进行84 -> 02 转换
     */
    public static String convertWkt(String wkt) {
        // 进行经纬度正则匹配
        List<String> points = ReUtil.findAll(Pattern.compile("\\d{1,3}\\.\\d{3,} \\d{1,3}\\.\\d{3,}", Pattern.MULTILINE), wkt, 0);
        boolean success = true;
        for (String point : points) {
            String[] split = point.split(" ");
            if (split.length == 2) {
                Point convertedLocation = iGdRestApiService.convertLocation(NumberUtil.toBigDecimal(split[0]), NumberUtil.toBigDecimal(split[1]), "");
                if (Objects.nonNull(convertedLocation)) {
                    String formatted = String.format("%s %s", convertedLocation.getLon(), convertedLocation.getLat());
                    log.info(String.format("Location convert from [%s] to [%s]", point, formatted));
                    wkt = wkt.replaceAll(point, formatted);
                } else {
                    success = false;
                    break;
                }
            }
        }
        if (Boolean.FALSE.equals(success)) {
            return null;
        }

        return wkt;
    }

    /**
     * 利用java工具进行 84 -> 02
     */
    public static String convertWkts(String wkt) {
        // 进行经纬度正则匹配
        List<String> points = ReUtil.findAll(Pattern.compile("\\d{1,3}\\.\\d{3,} \\d{1,3}\\.\\d{3,}", Pattern.MULTILINE), wkt, 0);
        boolean success = true;
        for (String point : points) {
            String[] split = point.split(" ");
            if (split.length == 2) {
                double[] convertedLocation = wgs84togcj02(Double.valueOf(split[0]), Double.valueOf(split[1]));
                if (convertedLocation.length == 2) {
                    String formatted = String.format("%s %s", convertedLocation[0], convertedLocation[1]);
                    // log.debug(String.format("Location convert from [%s] to [%s]", point, formatted));
                    wkt = wkt.replaceAll(point, formatted);
                } else {
                    success = false;
                    break;
                }
            }
        }
        if (Boolean.FALSE.equals(success)) {
            return null;
        }

        return wkt;
    }


    /**
     * 将边界里面经纬度精确到小数点6位
     */
    public static String convertWktPoint6(String wkt) {

        List<String> points = ReUtil.findAll(Pattern.compile("\\d{1,3}\\.\\d{3,} \\d{1,3}\\.\\d{3,}", Pattern.MULTILINE), wkt, 0);

        boolean success = true;
        for (String point : points) {
            String[] split = point.split(" ");
            if (split.length == 2) {
                String formatted = String.format("%s %s", new BigDecimal(split[0]).setScale(6, RoundingMode.HALF_UP), new BigDecimal(split[1]).setScale(6, RoundingMode.UP));
                if (ObjectUtil.isNotEmpty(formatted)) {
                    log.info(String.format("Location convert from [%s] to [%s]", point, formatted));
                    wkt = wkt.replaceAll(point, formatted);
                } else {
                    success = false;
                    break;
                }
            }
        }
        if (Boolean.FALSE.equals(success)) {
            return null;
        }
        return wkt;
    }

    /**
     * 百度坐标系(BD-09)转火星坐标系(GCJ-02)
     */

    public static double[] bd09togcj02(double bd_lon, double bd_lat) {
        double x = bd_lon - 0.0065;
        double y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lng = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        return new double[]{gg_lng, gg_lat};
    }

    /**
     * WGS84转GCJ02(火星坐标系)
     */
    public static double[] wgs84togcj02(double lng, double lat) {
        if (out_of_china(lng, lat)) {
            return new double[]{lng, lat};
        }
        double dlat = transformlat(lng - 105.0, lat - 35.0);
        double dlng = transformlng(lng - 105.0, lat - 35.0);
        double radlat = lat / 180.0 * pi;
        double magic = Math.sin(radlat);
        magic = 1 - ee * magic * magic;
        double sqrtmagic = Math.sqrt(magic);
        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
        double mglat = lat + dlat;
        double mglng = lng + dlng;
        return new double[]{mglng, mglat};
    }

    /**
     * 经度转换
     */
    public static double transformlat(double lng, double lat) {
        double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    /**
     * 纬度转换
     */
    public static double transformlng(double lng, double lat) {
        double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
        ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0;
        return ret;
    }

    /**
     * 判断当前坐标是否在国内
     */
    public static boolean out_of_china(double lng, double lat) {
        if (lng < 72.004 || lng > 137.8347) {
            return true;
        } else if (lat < 0.8293 || lat > 55.8271) {
            return true;
        }
        return false;
    }


}
